#!/usr/bin/python2.6  
# -*- coding: utf-8 -*-

import xml.etree.ElementTree as etree
import sys

tree = None
root = None

def loadFile(url):
	global tree
	tree = etree.parse(url)
	global root
	root = tree.getroot()
	for e in root:
		if e.tag.lower() == "modules":
			root = e
			break


def printXML():
	print "----------------------------------------------------------"
	for c in root:
		print c.attrib["destPath"]

	print "----------------------------------------------------------"

def fastSort(mi, mx):
	
	global root
	start = mi
	end = mx
	
	#print "start: %d, end: %d, mi: %d, mx: %d" % (start, end, mi, mx)
	
	if mi >= mx:
		pass
	else:
		flag = 0
		#print "..........................................................."
		while mi < mx:

			doex = "Fasle"

			if flag == 0:
				if root[mi].attrib["destPath"] > root[mx].attrib["destPath"]:
					root[mi], root[mx] = root[mx], root[mi]
					flag = 1
					doex = "True"
				else:
					mx = mx - 1
			else:
				if root[mi].attrib["destPath"] > root[mx].attrib["destPath"]:
					root[mi], root[mx] = root[mx], root[mi]
					flag = 0
					doex = "True"
				else:
					mi = mi + 1

			#print "min: %d, max: %d, doExchange: %s" %(mi, mx, doex)
		#print "..........................................................."
		
		fastSort(start, mi - 1)
		fastSort(mx + 1, end)
	
if __name__ == "__main__":
	
	#input args processor
	args = sys.argv
	inputurl = None
	outputurl = None

	if (args[1] != "-i") or (args[3] != "-i"):
		inputurl = args[1] == "-i" and args[2] or args[4]
	else:
		print "need -i"
		exit()

	if (args[1] != "-o") or (args[3] != "-o"):
		outputurl = args[1] == "-o" and args[2] or args[4]
	else:
		print "need -o"
		exit()

	print "InputURL: %s,\tOutputURL: %s" % (inputurl, outputurl)

	print "load xml file ......"
	
	loadFile(inputurl)
	
	print "success ! get root length is %d" % len(root)
	
	#print "primary elements sequence like this:"
	#printXML()
	
	print "start clean ......"
	
	fastSort(0, len(root) - 1)
	
	#print "sorted elements sequence like this:"
	#printXML()
	
	tree.write(outputurl)

	print "clean up !"
